from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from .models import UserProfile
import json
import os
from datetime import datetime

# 导入其他模块的模型来获取统计数据
from community.models import Post
from challenge.models import UserAnswer
from carbon.models import CarbonFootprint
from backed.pagination import get_pagination_params, paginate_queryset


@csrf_exempt
@login_required
@require_http_methods(["GET", "PUT"])
def user_profile_view(request):
    """
    用户信息管理接口
    GET /xiangsu/user/profile/ - 获取用户扩展信息
    PUT /xiangsu/user/profile/ - 更新用户扩展信息
    """
    try:
        # 获取或创建用户扩展信息
        profile, created = UserProfile.objects.get_or_create(user=request.user)
        
        if request.method == 'GET':
            return JsonResponse({
                'success': True,
                'data': {
                    'user_id': request.user.id,
                    'username': request.user.username,
                    'email': request.user.email,
                    'nickname': profile.nickname,
                    'gender': profile.gender,
                    'phone': profile.phone,
                    'avatar': profile.avatar,
                    'bio': profile.bio,
                    'points': profile.points,
                    'created_at': profile.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                    'updated_at': profile.updated_at.strftime('%Y-%m-%d %H:%M:%S')
                }
            }, status=200)
            
        elif request.method == 'PUT':
            # 支持JSON格式和表单格式
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
            
            # 更新可修改字段
            if 'nickname' in data:
                profile.nickname = data['nickname']
            if 'gender' in data:
                profile.gender = data['gender']
            if 'phone' in data:
                profile.phone = data['phone']
            if 'bio' in data:
                profile.bio = data['bio']
            
            # 处理头像文件上传
            if 'avatar' in request.FILES:
                avatar_file = request.FILES['avatar']
                
                # 验证文件类型
                allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
                if avatar_file.content_type not in allowed_types:
                    return JsonResponse({
                        'success': False,
                        'message': '只支持 JPEG、PNG、GIF 和 WebP 格式的图片'
                    }, status=400)
                
                # 验证文件大小（限制为5MB）
                if avatar_file.size > 5 * 1024 * 1024:
                    return JsonResponse({
                        'success': False,
                        'message': '头像文件大小不能超过5MB'
                    }, status=400)
                
                # 处理文件名，避免冲突
                timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
                file_extension = os.path.splitext(avatar_file.name)[1]
                filename = f"avatar_{request.user.id}_{timestamp}{file_extension}"
                
                # 保存文件
                profile.avatar.save(filename, avatar_file)
            
            profile.save()
            
            return JsonResponse({
                'success': True,
                'message': '用户信息更新成功',
                'data': {
                    'nickname': profile.nickname,
                    'gender': profile.gender,
                    'phone': profile.phone,
                    'avatar': profile.avatar if profile.avatar else None,
                    'bio': profile.bio,
                    'points': profile.points,
                    'updated_at': profile.updated_at.strftime('%Y-%m-%d %H:%M:%S')
                }
            }, status=200)
            
    except json.JSONDecodeError:
        return JsonResponse({
            'success': False,
            'message': '无效的JSON格式'
        }, status=400)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'操作失败: {str(e)}'
        }, status=500)


@csrf_exempt
@login_required
@require_http_methods(["GET"])
def user_points_view(request):
    """
    获取用户积分信息
    GET /xiangsu/user/points/
    """
    try:
        profile, created = UserProfile.objects.get_or_create(user=request.user)
        
        return JsonResponse({
            'success': True,
            'data': {
                'user_id': request.user.id,
                'username': request.user.username,
                'points': profile.points,
                'total_points': profile.points  # 未来可扩展为累计积分
            }
        }, status=200)
        
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'获取积分信息失败: {str(e)}'
        }, status=500)


@csrf_exempt
@login_required
@require_http_methods(["POST"])
def upload_avatar_view(request):
    """
    头像上传接口
    POST /xiangsu/user/upload-avatar/ - 上传用户头像
    """
    try:
        # 获取或创建用户扩展信息
        profile, created = UserProfile.objects.get_or_create(user=request.user)
        
        # 检查是否有文件上传
        if 'avatar' not in request.FILES:
            return JsonResponse({
                'success': False,
                'message': '请选择要上传的头像文件'
            }, status=400)
        
        avatar_file = request.FILES['avatar']
        
        # 验证文件类型
        allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
        if avatar_file.content_type not in allowed_types:
            return JsonResponse({
                'success': False,
                'message': '只支持 JPEG、PNG、GIF 和 WebP 格式的图片'
            }, status=400)
        
        # 验证文件大小（限制为5MB）
        if avatar_file.size > 5 * 1024 * 1024:
            return JsonResponse({
                'success': False,
                'message': '头像文件大小不能超过5MB'
            }, status=400)
        
        # 处理文件名，避免冲突
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        file_extension = os.path.splitext(avatar_file.name)[1]
        filename = f"avatar_{request.user.id}_{timestamp}{file_extension}"
        
        # 保存文件
        profile.avatar.save(filename, avatar_file)
        profile.save()
        
        return JsonResponse({
            'success': True,
            'message': '头像上传成功',
            'data': {
                'avatar_url': profile.avatar if profile.avatar else None,
                'avatar_filename': filename
            }
        }, status=200)
        
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'头像上传失败: {str(e)}'
        }, status=500)


@csrf_exempt
@login_required
@require_http_methods(["GET"])
def user_statistics_view(request):
    """
    获取用户统计数据接口
    GET /xiangsu/user/statistics/
    返回用户的发布动态数、完成挑战数、碳足迹记录数
    """
    try:
        user_id = request.user.id
        
        # 获取发布动态数
        posts_count = Post.objects.filter(user=request.user).count()
        
        # 获取完成挑战数（正确回答的题目数）
        # 为了避免重复计算同一关卡的多次尝试，我们需要获取用户正确回答的唯一题目数
        completed_challenges_count = UserAnswer.objects.filter(
            user=request.user, 
            is_correct=True
        ).values('question').distinct().count()
        
        # 获取碳足迹记录数
        carbon_records_count = CarbonFootprint.objects.filter(user=request.user).count()
        
        return JsonResponse({
            'success': True,
            'data': {
                'user_id': user_id,
                'username': request.user.username,
                'posts_count': posts_count,
                'completed_challenges_count': completed_challenges_count,
                'carbon_records_count': carbon_records_count
            }
        }, status=200)
        
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'获取用户统计数据失败: {str(e)}'
        }, status=500)


@csrf_exempt
@require_http_methods(["GET"])
def user_leaderboard_view(request):
    """
    用户积分排行榜（碳积分）
    GET /xiangsu/user/leaderboard/
    支持查询参数：page, page_size；兼容 limit
    返回字段：rank, user_id, username, points, avatar
    """
    try:
        # 支持 page/page_size，兼容 limit
        if 'limit' in request.GET and 'page_size' not in request.GET:
            page = 1
            try:
                page_size = int(request.GET.get('limit', 10))
            except Exception:
                page_size = 10
        else:
            page, page_size = get_pagination_params(request, default_page_size=10, max_page_size=100)

        qs = UserProfile.objects.select_related('user').order_by('-points')
        page_qs, meta = paginate_queryset(qs, page, page_size)

        start_index = (meta['page'] - 1) * meta['page_size']
        items = []
        for i, profile in enumerate(page_qs):
            items.append({
                'rank': start_index + i + 1,
                'user_id': profile.user.id if profile.user else None,
                'username': profile.user.username if profile.user else '未知用户',
                'points': int(profile.points or 0),
                'avatar': profile.avatar or ''
            })

        return JsonResponse({
            'success': True,
            'data': {
                'items': items,
                'meta': meta
            }
        }, status=200)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'获取用户积分排行榜失败: {str(e)}'
        }, status=500)


# 轮播图接口已移至社区模块
